package com.sds.servlet;


import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.sds.ai.impl.data.logging.ChatSession;
import com.sds.ai.impl.provider.DataProviderImpl;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;

@Singleton
public class ShowChatLogServlet extends HttpServlet {

    private final Logger LOGGER = Logger.getLogger(getClass().getName());

    private final DataProviderImpl dataProvider;

    @Inject
    public ShowChatLogServlet(DataProviderImpl dataProvider) {
        this.dataProvider = dataProvider;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getOutputStream().println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n");
        resp.getOutputStream().println("        \"http://www.w3.org/TR/html4/loose.dtd\">");
        resp.getOutputStream().println("<html>");
        resp.getOutputStream().println("<head>");
        resp.getOutputStream().println("<meta content=\"text/html\" charset=\"UTF-8\">");
        resp.getOutputStream().println("</head>");
        resp.getOutputStream().println("<body>");
        SimpleDateFormat sdf = new SimpleDateFormat();
        for (ChatSession chatSession : dataProvider.getAll(ChatSession.class)) {
            resp.getOutputStream().println("<br/>START:" + sdf.format(chatSession.getStart()));
            resp.getOutputStream().println("<br/>END:" + sdf.format(chatSession.getEnd()));
            resp.getOutputStream().println(encodeHTML(chatSession.getMessages()).replaceAll("\n", "<br/>"));
            resp.getOutputStream().println("<hr/>");
        }
        resp.getOutputStream().println("</body>");
        resp.getOutputStream().println("</html>");
//        try {
//            Marshaller marshaller = JAXBContext.newInstance(ChatSessions.class).createMarshaller();
//            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//            marshaller.marshal(chatSessions, resp.getWriter());
//        } catch (JAXBException e) {
//            LOGGER.error(e.getMessage(), e);
//        }
    }

    private String encodeHTML(String s) {
        StringBuffer out = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c > 127 || c == '"' || c == '<' || c == '>') {
                out.append("&#" + (int) c + ";");
            } else {
                out.append(c);
            }
        }
        return out.toString();
    }
}

